##################################
#-*- coding:utf8 -*-             #
import malware
import re     

class script_check(object):
    def mal_or_not(self,node):
        if self.mal_url(node)==False:
            return False
        
    def mal_url(self,node):
        if malware.url_check(node.injection_url)==False or node.injection_url_mal==1:
            print 'malicous=',node.url
            return True
        else:
            return False    
        
class script_result(object):
    def mal_or_not(self):
        return self.url_check.mal_or_not(self)
    def get_href(self):
        try:    
            result=re.search('http://((([\w-]+\.)+([\w-]+))(/[\w-]+)*)',self.h['href']).groups()
            self.href=result[0]                                    
        except:
            self.href=''
            pass
        
    def get_title(self):
        self.title=''
        try:                                        
            self.title=re.search('(/title\s*>\s*<\s*script)(\s+src="*(http://)?((([\w-]+\.)+[\w-]+)(/[\w-]+)*/([\w-]+.[jJ][Ss]))"*></script>)*',self.h['hreftxt']).groups()
            return
        except:            
            pass
        
    def get_injection_url(self):
        self.injection_url_mal=0
        self.injection_url=""
        try:            
            textreg=re.search('/title\s*>\s*<\s*script\s+src="*(http://)?((([\w-]+\.)+([\w-]+))(/[\w-]+)*/([\w-]+.[jJ][Ss]))"*></script>',self.h['text']).groups()
            self.injection_url=textreg[0]+textreg[1]
            return
        except Exception,ex:
            pass
        
        try:
            textreg=re.search('src="*(http://)?((([\w-]+\.)+([\w-]+))(/[\w-]+)*/([\w-]+.[jJ][Ss]))',self.h['text']).groups()
            self.injection_url=textreg[0]+textreg[1]
            return
        except Exception,ex:                
            pass    
       
        try:
            textreg=re.search('http://((([\w-]+\.)+([\w-]+))(/[\w-]+)*)',self.h['text']).groups()
            self.injection_url='http://'+textreg[0]
            return
        except Exception,ex:                            
            pass
        
        try:
            textreg=re.search('http://((%+((\d|\w){2}))+)',self.h['text']).groups()
            self.injection_url='http://'+textreg[0]
            self.injection_url_mal=1
            return
        except Exception,ex:
            print   self.h['text']              
            pass    
        #[\da-f-A-F]
            

    def __init__(self,element):
        self.node=''
        self.h=element
        self.url=self.h['href']            
        self.get_injection_url()
        self.get_href()
        self.get_title()
        self.url_check=script_check()
          
def handle(element):
    x=script_result(element)
    x.mal_or_not()        
    
    
     
        